package top.truehaku.generator.starter;


import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateModelException;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import top.truehaku.generator.code.application.vo.ContextInfo;


import java.io.File;
import java.io.IOException;

@Configuration
@ComponentScan("top.truehaku.generator.code")
@EnableConfigurationProperties({GlobalCodeProperties.class, DataSourceProperties.class})
public class CodeAutoConfiguration {

    @Bean
    public JdbcTemplate template(DataSourceProperties properties){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(properties.getDriverClassName());
        dataSource.setUrl(properties.getUrl());
        dataSource.setUsername(properties.getUsername());
        dataSource.setPassword(properties.getPassword());
        return new JdbcTemplate(dataSource);
    }


    @Bean(name = "freemarker-configuration")
    public freemarker.template.Configuration getConfiguration(GlobalCodeProperties properties){
        freemarker.template.Configuration configuration;
        try {
            configuration = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_28);
            configuration.setDefaultEncoding("UTF-8");
            configuration.setTemplateUpdateDelayMilliseconds(0);
            configuration.setDirectoryForTemplateLoading(new File(properties.getTemplatePath()));//绝对定位寻找模板
            configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            configuration.setSharedVariable("context",new ContextInfo(properties));
        }catch (IOException exception){
            exception.printStackTrace();
            throw new RuntimeException("找不到模板位置");
        }catch (TemplateModelException exception){
            throw new RuntimeException("加载freemarker全局配置失败");
        }
        return configuration;
    }

}